//
//  CheekEncounterViewController.m
//  CheekiOS
//
//  Created by mac on 2017/7/11.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "CheekEncounterViewController.h"
#import "NewPagedFlowView.h"
#import "PGIndexBannerSubiew.h"
#import "HQConversationViewController.h"
#import "IconScrollView.h"
#import "CheekMessageAlertView.h"

@interface CheekEncounterViewController ()<NewPagedFlowViewDelegate, NewPagedFlowViewDataSource,IconScrollViewDelegate,PGIndexBannerSubiewDelegate,CheekMessageAlertViewDelegate>

/**
 *  图片数组
 */
@property (nonatomic, strong) NSMutableArray *dateSource;
/** <#描述#> */
@property (nonatomic,strong) IconScrollView * iconScrollView;
/** <#描述#> */
@property (nonatomic,weak) NewPagedFlowView * pagedFlowView;
/** 页数*/
@property (nonatomic, assign)NSInteger page;
/** 数量 */
@property (nonatomic, assign)NSInteger rows;
/** 第几个 */
@property (nonatomic, assign)NSInteger Howmany;
/**
 
 */
@property (nonatomic, strong)CheekMessageAlertView *messageAlert;

@property (nonatomic, strong) UIImageView *VodepUserImg;
@property (nonatomic, strong) UILabel *NoUserLable;

@property (nonatomic, strong) NSNumber *UserTypehidden;

@property (nonatomic, assign) NSInteger integerPath;

@property (nonatomic, strong)UserpersionlInfoModel *model;
@end

@implementation CheekEncounterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self selfTitleFontColor];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"遇到过的人";
    _page  = 1;
    _rows = 30;
    _Howmany = 0;
    UIButton *screeningBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [screeningBtn addTarget:self action:@selector(screeningBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    [screeningBtn setTitle:@"清空" forState:UIControlStateNormal];
    screeningBtn.titleLabel.font = FontP(17);
    [screeningBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    screeningBtn.frame = CGRectMake(0, 0, 44, 44);
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc ] initWithCustomView:screeningBtn];
    self.navigationItem.rightBarButtonItem = backItem;
    
    self.VodepUserImg = [[UIImageView alloc] initWithFrame:CGRectMake(15, 20, KScreenWidth-30, KScreenHeight*0.55)];
    self.VodepUserImg.hidden = YES;
    self.VodepUserImg.image = [UIImage imageNamed:@"viedo_met_ai"];
    self.VodepUserImg.contentMode = UIViewContentModeScaleToFill;
    [self.view addSubview:self.VodepUserImg];
    
    _NoUserLable = [[UILabel alloc] initWithFrame:CGRectMake(0, self.VodepUserImg.bottom+35, KScreenWidth, 35)];
    _NoUserLable.text = @"你还没有遇见TA呦，快去遇见吧...";
    _NoUserLable.textColor = ColorI(0x2e353f);
    _NoUserLable.textAlignment = NSTextAlignmentCenter;
    _NoUserLable.font = FontP(17);
    _NoUserLable.hidden = YES;
    [self.view addSubview:_NoUserLable];
    
    _dateSource = [[NSMutableArray alloc] init];
    [self requestgetCommonOpen];
    [self UserInfoRequestDate];
    
    

    
}
- (void)requestgetCommonOpen{
    
    [HcardHttpmanager getCommonOpen:[HQHttpManager getUserId] success:^(id result) {
        if([result[@"code"] isEqualToString:@"ok"]){
            
            _UserTypehidden = result[@"res"][@"open"];
            
            
            [self requestDate];

            
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}
- (void)UserInfoRequestDate{
    
    [HcardHttpmanager getPersionalUserInfosuccess:^(id sucess) {
        self.model = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];
        
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)requestDate{
WEAKSELF
    [CheekVodeRequest getCheekVideoChatListUid:[HQHttpManager getUserId] page:_page rows:_rows success:^(id sucess) {
        
        _dateSource = [CheekVodeModel mj_objectArrayWithKeyValuesArray:sucess[@"res"]];
        
        if (_dateSource.count > 0) {
            weakSelf.VodepUserImg.hidden = YES;
            weakSelf.NoUserLable.hidden = YES;
                [weakSelf setupUI];
            
        }else{
            weakSelf.VodepUserImg.hidden = NO;
            weakSelf.NoUserLable.hidden = NO;
                   }
        
    } failure:^(NSError *error) {
        
    }];

}

//清空
- (void)screeningBtnAction{
    
    if (_dateSource.count <= 0 ) {
        [SVProgressHUD showWithStatus:@"已经没有更多数据啦，无法清空"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定要清空吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [CheekVodeRequest getCheekDelVideoUid:[HQHttpManager getUserId] Wid:@"" empty:@"1" success:^(id sucess) {
            [_dateSource removeAllObjects];
            [self.iconScrollView removeFromSuperview];
            [self.pagedFlowView reloadData];
        } failure:^(NSError *error) {
            
        }];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    
    }];
    [alertVC addAction:confirAction];
    [alertVC addAction:cancel];
    [self.navigationController presentViewController:alertVC animated:YES completion:nil];
    
}
- (void)setupUI {
    
    
    NewPagedFlowView *pageFlowView = [[NewPagedFlowView alloc] initWithFrame:CGRectMake(0, 15, KScreenWidth, KScreenHeight*0.75)];
    pageFlowView.delegate = self;
    pageFlowView.dataSource = self;
    pageFlowView.minimumPageAlpha = 0.1;
    pageFlowView.isCarousel = NO;
    pageFlowView.orientation = NewPagedFlowViewOrientationHorizontal;
    pageFlowView.isOpenAutoScroll = YES;
    
    
    //初始化pageControl
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, pageFlowView.frame.size.height - 32, 200, 8)];
    pageFlowView.pageControl = pageControl;
    //    [pageFlowView addSubview:pageControl];
    
    /****************************
     使用导航控制器(UINavigationController)
     如果控制器中不存在UIScrollView或者继承自UIScrollView的UI控件
     请使用UIScrollView作为NewPagedFlowView的容器View,才会显示正常,如下
     *****************************/
    
    UIScrollView *bottomScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [bottomScrollView addSubview:pageFlowView];
    
    [pageFlowView reloadData];
    
    [self.view addSubview:bottomScrollView];
    self.pagedFlowView = pageFlowView;
    
    self.iconScrollView = [[IconScrollView alloc] initWithFrame:CGRectMake(0, pageFlowView.bottom+20, KScreenWidth, 60*SCREEN_WIDTH_RATIO47)];

    
    _iconScrollView.imgArr = self.dateSource;
    _iconScrollView.delegate = self;
    [self.view addSubview:_iconScrollView];
    [_iconScrollView chooseImageWithIndex:0];
    
    
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark NewPagedFlowView Delegate

- (CGSize)sizeForPageInFlowView:(NewPagedFlowView *)flowView {
    return CGSizeMake(KScreenWidth - 60, (KScreenHeight*0.75 - 60));
}
- (void)didSelectCell:(UIView *)subView withSubViewIndex:(NSInteger)subIndex {
    
    NSLog(@"点击了第%ld张图",(long)subIndex + 1);
 
}

#pragma mark NewPagedFlowView Datasource
- (NSInteger)numberOfPagesInFlowView:(NewPagedFlowView *)flowView {
    
    return self.dateSource.count;
    
}

- (UIView *)flowView:(NewPagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    
    PGIndexBannerSubiew *bannerView = (PGIndexBannerSubiew *)[flowView dequeueReusableCell];

    if (!bannerView) {
        bannerView = [[PGIndexBannerSubiew alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth-60, KScreenHeight*0.75)];
        bannerView.delegate = self;

        bannerView.tag = index;
    }

    //在这里下载网络图片
    CheekVodeModel *model = _dateSource[index];
    [bannerView.mainImageView sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(model.photo)] placeholderImage:[UIImage imageNamed:@"llustration"]];

    
    bannerView.nameLab.text = model.nickName;
    
    if (model.sex == 0) {
        [bannerView.ageBtn setBackgroundColor:ColorI(0xf28484)];
        
        [bannerView.ageBtn setImage:[UIImage imageNamed:@"female"] forState:UIControlStateNormal];
    }else{
        [bannerView.ageBtn setBackgroundColor:ColorI(0x84b9f2)];
        
        [bannerView.ageBtn setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
    }
    //年龄
    [bannerView.ageBtn setTitle:model.age  forState:UIControlStateNormal];
    //星座
    bannerView.constellationLab.backgroundColor = [self getColorWithStr:model.star];
    
    bannerView.constellationLab.text = model.star;
    
    bannerView.address.text = model.location;
    
    
    return bannerView;
}

- (void)didScrollToPage:(NSInteger)pageNumber inFlowView:(NewPagedFlowView *)flowView {
    
    NSLog(@"ViewController 滚动到了第%ld页",pageNumber);
    
    _Howmany = pageNumber;
    
    [self.iconScrollView chooseImageWithIndex:pageNumber];
}
#pragma ---mark---IconScrollViewDelegate
- (void)iconScrollView:(IconScrollView *)scrollView chooseIconAtIndex:(NSInteger)index{
    
    [self.pagedFlowView scrollToPage:index];
}




- (UIColor *)getColorWithStr:(NSString *)starStr{
    
    NSArray * starArr = @[@"白羊座",@"天秤座",@"金牛座",@"天蝎座",@"双子座",@"射手座",@"巨蟹座",@"摩羯座",@"狮子座",@"处女座",@"双鱼座"];
    NSArray * colorArr = @[ColorI(0xd80808),ColorI(0xec3db0),ColorI(0x2898df),ColorI(0xa651c9),ColorI(0xff6839),ColorI(0x77ca69),ColorI(0xd16739),ColorI(0x30d3d5),ColorI(0x19d7ad),ColorI(0xecac3d),ColorI(0x32b576)];
    
    
    for (NSString * star in starArr) {
        if ([star isEqualToString:starStr]) {
            NSInteger index = [starArr indexOfObject:star];
            if (colorArr[index]) {
                return colorArr[index];
            }
        }
    }
    return ColorI(0xd80808);
}

#pragma mark ===========删除========消息========代理=======

-(void)indexBannerSubiew:(PGIndexBannerSubiew *)subiew removeBtnClick:(UIButton *)sender{

    NSInteger index = self.pagedFlowView.currentPageIndex;
  
    CheekVodeModel *model = _dateSource[index];

    
    [CheekVodeRequest getCheekDelVideoUid:[HQHttpManager getUserId] Wid:model.uid empty:@"" success:^(id sucess) {
     
        if ([sucess[@"code"] isEqualToString:@"ok"]) {
            [self.dateSource removeObjectAtIndex:index];
            [self.pagedFlowView reloadData];
            [self.iconScrollView removeAtIndex:index];
            if (self.iconScrollView.imgArr.count > 0) {
                [self.iconScrollView chooseImageWithIndex:0];
            }
        }
        

    } failure:^(NSError *error) {
        
    }];
    
    
}
//_UserTypehidden

-(void)messageBtnAction:(UIButton *)sender{

    
    _integerPath = sender.tag;
    
    
    CheekVodeModel *model = _dateSource[_integerPath];
    
    if ([model.moneyStatus isEqualToString:@"1"]) {
        HQConversationViewController *conversationVC = [[HQConversationViewController alloc]init];
        conversationVC.conversationType = ConversationType_PRIVATE;
        NSString *str = model.uid;
        conversationVC.targetId = [NSString stringWithFormat:@"%@",str];
        conversationVC.title = model.nickName;
        conversationVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:conversationVC animated:YES];
        
    }else{
        
        if ([_UserTypehidden isEqualToNumber:@1]) {
            [self messageAlertAction];
            
        }else{
            HQConversationViewController *conversationVC = [[HQConversationViewController alloc]init];
            conversationVC.conversationType = ConversationType_PRIVATE;
            NSString *str = model.uid;
            conversationVC.targetId = [NSString stringWithFormat:@"%@",str];
            conversationVC.title = model.nickName;
            conversationVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:conversationVC animated:YES];
            
        }
        
        
    }

    
}

//弹框
- (void)messageAlertAction{
    
    self.messageAlert = [[CheekMessageAlertView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    self.messageAlert.delegate = self;
    
    if (self.model.charm > 20) {
        [self.messageAlert CheekAlertTitle:@"需要花费20钻石" text:@"和TA【视频聊天】和【文字聊天】" determineTitle:@"确定" determineBtnTage:1];
    }else{
        [self.messageAlert CheekAlertTitle:@"需要花费20钻石" text:@"和TA【视频聊天】和【文字聊天】" determineTitle:@"去购买" determineBtnTage:0];
    }
    [self animationWithView:self.messageAlert duration:0.3];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.messageAlert.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        
        
        [self.view addSubview:self.messageAlert];
    }];
    
}

- (void)animationWithView:(UIView *)view duration:(CFTimeInterval)duration{
    
    CAKeyframeAnimation * animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = duration;
    animation.removedOnCompletion = NO;
    
    animation.fillMode = kCAFillModeForwards;
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    //    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    
    animation.values = values;
    animation.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
    
    [view.layer addAnimation:animation forKey:nil];
}
@end
